<template>
  <div
    v-loading="isLoading"
    class="panel-property"
  >
    <div class="content">
      <PanelLabelOverflowTooltip
        ref="panelLabelOverflowTooltip"
        :component-style="form.componentStyle"
      />
      <el-form
        ref="form"
        v-panel-label-overflow-tooltip="getPanelLabelOverflowTooltip()"
        class="prop-form"
        label-position="right"
        :model="form"
        :rules="rules"
        label-width="30%"
      >
        <div class="config-table">
          <div class="top-btns">
            <el-button
              plain
              class="btn-sure"
              type="primary"
              size="default"
              icon="FolderAdd"
              :disabled="groupAddDisable"
              @click.stop="addNewRow(groupTemp, groupItem, 'group')"
            >
              {{ $demoi18n('panel.btn.addGroup') }}
            </el-button>
            <BaseOption
              :form="form"
              option="tooltip"
              :widget-instance-id="widgetInstanceId"
              :config="config"
            />
          </div>
          <el-table
            class="config-panel-table mapping-table"
            :data="form.group"
            :row-style="{ height: '25px' }"
            :header-row-style="{ height: '25px' }"
            max-height="180"
            :header-cell-style="{ lineHeight: '15px' }"
          >
            <el-table-column
              prop="icon"
              :label="$demoi18n('word.icon')"
              width="45"
              :render-header="renderTableHeader"
            >
              <template #default="scope">
                <IconEditor
                  :icon="scope.row.icon"
                  :component-style="form.componentStyle"
                  :has-sync="true"
                  @save="saveIcon($event, scope.row)"
                  @delete="deleteIcon($event, scope.row)"
                  @sync="syncIcons($event, form.group)"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              :label="$demoi18n('word.name')"
              min-width="110"
              :render-header="renderTableHeader"
            >
              <template #default="scope">
                <VsFormItem
                  :prop="`group[${scope.$index}].name`"
                  :rules="
                    generateRules({
                      required: false,
                    })
                  "
                >
                  <ValueInputer
                    v-model:value="scope.row.name"
                    :enum-values="nameList"
                  />
                </VsFormItem>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              :label="$demoi18n('panel.label.widthPx')"
              min-width="60"
              :render-header="renderTableHeader"
            >
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.width"
                  style="width:100%"
                  size="default"
                  :controls="false"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column min-width="30">
              <template #default="scope">
                <el-button
                  icon="Delete"
                  :link="true"
                  type="primary"
                  :disabled="groupDelDisable"
                  @click.stop="deleteCurRow(scope.row, 'group')"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="config-table">
          <el-button
            plain
            class="btn-sure"
            type="primary"
            size="default"
            icon="CirclePlus"
            :disabled="dataAddDisable"
            @click.stop="addNewRow(dataTemp, dataItem, 'data')"
          >
            {{ $demoi18n('btn.addNew') }}
          </el-button>
          <el-table
            class="config-panel-table mapping-table"
            :data="form.data"
            :row-style="{ height: '25px' }"
            :header-row-style="{ height: '25px' }"
            max-height="135"
            :header-cell-style="{ lineHeight: '15px' }"
          >
            <el-table-column
              :label="$demoi18n('panel.th.class')"
              :width="45"
              :render-header="renderTableHeader"
            >
              <template #default="scope">
                {{ `y${scope.$index + 1}` }}
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              :label="$demoi18n('word.name')"
              min-width="110"
              :render-header="renderTableHeader"
            >
              <template #default="scope">
                <VsFormItem
                  :prop="`data[${scope.$index}].name`"
                  :rules="
                    generateRules({
                      required: false,
                    })
                  "
                >
                  <el-input
                    v-model="scope.row.name"
                    size="default"
                  ></el-input>
                </VsFormItem>
              </template>
            </el-table-column>
            <el-table-column
              prop="unit"
              :label="$demoi18n('word.unit')"
              min-width="60"
              :render-header="renderTableHeader"
            >
              <template #default="scope">
                <VsFormItem
                  :prop="`data[${scope.$index}].unit`"
                  :rules="
                    generateRules({
                      required: false,
                    })
                  "
                >
                  <el-input
                    v-model="scope.row.unit"
                    size="default"
                  ></el-input>
                </VsFormItem>
              </template>
            </el-table-column>

            <el-table-column min-width="30">
              <template #default="scope">
                <el-button
                  icon="Delete"
                  :link="true"
                  type="primary"
                  :disabled="dataDelDisable"
                  @click.stop="deleteCurRow(scope.row, 'data')"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <OptionCollapse>
          <el-collapse-item
            :title="$demoi18n('echart.setting.component')"
            name="cssStyle.grid"
          >
            <BaseOption
              :form="form"
              option="cssStyle.grid"
              :df-css-style-attrs="dfCssStyleAttrs.grid"
            />
            <VsFormItem
              :label="$demoi18n('panel.cssStyle.bgColor')"
              class="range-content"
              prop="backgroundColor"
            >
              <ColorPicker v-model:value="form.backgroundColor" />
            </VsFormItem>
          </el-collapse-item>

          <el-collapse-item
            :title="$demoi18n('panel.label.titleStyle')"
            name="cssStyle.title"
          >
            <BaseOption
              :form="form"
              option="title"
            />
            <BaseOption
              :form="form"
              option="cssStyle.title"
              :df-css-style-attrs="dfCssStyleAttrs.title"
            />
            <BaseOption :form="form" option="isTitleSignVisiable" />
            <BaseOption v-if="form.isTitleSignVisiable" :form="form" option="signMarginLeft" />
            <BaseOption v-if="form.isTitleSignVisiable" :form="form" option="verticalLineBackgroundColor" />
          </el-collapse-item>

          <el-collapse-item :title="$demoi18n('label.fontStyle')">
            <el-tooltip
              placement="top-end"
              :show-arrow="false"
              :effect="xvueTheme"
              popper-class="ring-help-description"
            >
              <span class="help-description">
                <el-icon><QuestionFilled /></el-icon>
                {{ $demoi18n('label.helpDescription') }}
              </span>
              <template #content>
                <div
                  :style="{ background: xvueTheme === 'light' ? '#fff' : '#000' }"
                >
                  <img
                    :src="img"
                    alt
                  />
                </div>
              </template>
            </el-tooltip>
            <el-tabs
              v-model="activeName"
              class="panel-tabs"
            >
              <el-tab-pane
                :label="$demoi18n('label.indicatorName')"
                name="first"
              >
                <BaseOption
                  :form="form"
                  option="cssStyle.indexName"
                  :df-css-style-attrs="dfCssStyleAttrs.indexName"
                />
              </el-tab-pane>
              <el-tab-pane
                :label="$demoi18n('panel.th.indicatorUnit')"
                name="second"
              >
                <BaseOption
                  :form="form"
                  option="cssStyle.unit"
                  :df-css-style-attrs="dfCssStyleAttrs.unit"
                />
              </el-tab-pane>
              <el-tab-pane
                :label="$demoi18n('panel.label.value')"
                name="third"
              >
                <BaseOption
                  :form="form"
                  option="cssStyle.value"
                  :df-css-style-attrs="dfCssStyleAttrs.value"
                />
              </el-tab-pane>
              <el-tab-pane
                :label="$demoi18n('label.groupName')"
                name="fourth"
              >
                <BaseOption
                  :form="form"
                  option="cssStyle.groupName"
                  :df-css-style-attrs="dfCssStyleAttrs.groupName"
                />
              </el-tab-pane>
            </el-tabs>
          </el-collapse-item>
          <BaseOption
            :form="form"
            option="noDataPromptSetting"
          />
        </OptionCollapse>
        <BaseOption
          :form="form"
          option="componentStyle"
          @change="changeColorVal"
        />
      </el-form>
    </div>
    <PanelPropertyBottom :config="config" :widgetInstanceId="widgetInstanceId" :form="form" />
  </div>
</template>
<script lang='jsx'>
import ColorPopover from '@/components/color-popover/colorPopover';
import OptionCollapse from '@/components/common/base-option/option-collapse/option-collapse.vue';
import ColorPicker from '@/components/common/color-picker/color-picker.vue';
import IconEditor from '@/components/common/icon/icon-editor.vue';
import PanelLabelOverflowTooltip from '@/components/common/overflow-tooltip/overflow-tooltip.vue';
import Range from '@/components/common/range/range.vue';
import ValueInputer from '@/components/common/value-inputer/value-inputer.vue';
import imgUploadBase from '@/mixin/img-upload-base.js';
import panelPropertyBase from '@/mixin/panel-property-base.js';
import BaseOption from '../../common/base-option/base-option.vue';
import colorGroup from './colorGroup.js';
import dfCssStyleAttrs from './cssStyle-default.js';
import EventBus from '@/event-bus/EventBus.js';

export default {
  name: 'PanelProperty',
  components: {
    ColorPopover,
    BaseOption,
    ValueInputer,
    OptionCollapse,
    IconEditor,
    PanelLabelOverflowTooltip,
    Range,
    ColorPicker,
  },
  mixins: [imgUploadBase, panelPropertyBase],
  props: ['config', 'widgetInstanceId', 'widget'],
  emits: ['updateHorizontalFormData'],
  data() {
    return {
      activeColorRadio: '#2D8CF0', // 单选框选中时的颜色
      colorGroup: colorGroup,
      predefineColors: ['#ff5071'],
      isLoading: false,
      countOptions: [],
      form: {},
      groupItem: {
        name: '',
        icon: '',
        iconSmall: '',
        uploadList: '',
        imgUrl: '',
        children: [],
        width: 120,
      },
      groupTemp: {},
      dataItem: {
        name: '',
        unit: '',
      },
      dataTemp: {},
      dataDelDisable: true,
      groupDelDisable: true,
      dataAddDisable: false,
      groupAddDisable: false,
      nameList: [],
      dataRange: [2],
      groupRange: [2],
      dfCssStyleAttrs: {},
      activeName: 'first',
    };
  },
  computed: {
    img() {
      if (this.xvueLanguage === 'zh-CN') {
        return new URL(`./horizontal_indicator_chart_zh_${this.xvueTheme}.png`, import.meta.url).href;
      } else {
        return new URL(`./horizontal_indicator_chart_en_${this.xvueTheme}.png`, import.meta.url).href;
      }
    },
  },
  watch: {
    'form.group': {
      handler() {
        const len = this.form.group.length;
        this.groupAddDisable = len >= 30;
        this.checkLimit();
      },
      deep: true,
    },
    'form.data'(val) {
      const dataCount = val.length;
      this.dataAddDisable = dataCount >= 30;
      this.dataDelDisable = dataCount <= this.dataRange[0];
    },
  },
  created() {
    // 读取配置
    if (this.config) {
      this.form = JSON.parse(JSON.stringify(this.config.config.property));
      this.form.imgSize = this.form.imgSize || 26;

      // 初始化配置数据
      this.initMultiConfigData();
    }
    EventBus.$on('updateHorizontalFormNewData', obj => {
      this.form.data.push(obj);
    });
    EventBus.$on(`apiDataChanged_${this.widgetInstanceId}`, this.apiDataChanged);
  },
  unmounted() {
    EventBus.$off('updateHorizontalFormNewData');
  },
  methods: {
    getPanelLabelOverflowTooltip() {
      return {
        parentComp: this,
      };
    },
    initMultiConfigData() {
      let groupCount = this.form.group.length;
      for (let i = groupCount; i < this.groupRange[0]; i++) {
        this.groupTemp = JSON.parse(JSON.stringify(this.groupItem));
        this.form.group.push(this.groupTemp);
      }
      groupCount = this.form.group.length;
      this.groupDelDisable = groupCount <= this.groupRange[0];
      if (!this.form.group[0].width) {
        for (let i = 0; i < groupCount; i++) {
          this.form.group[i].width = 120;
        }
      }
      let dataCount = this.form.data.length;
      for (let i = dataCount; i < this.dataRange[0]; i++) {
        this.dataTemp = JSON.parse(JSON.stringify(this.dataItem));
        this.form.data.push(this.dataTemp);
      }
      dataCount = this.form.data.length;
      this.dataDelDisable = dataCount <= this.dataRange[0];
      this.dfCssStyleAttrs = dfCssStyleAttrs;
    },
    addNewRow(temp, item, group) {
      const _temp = JSON.parse(JSON.stringify(item));
      this.form[group].push(_temp);
      const count = this.form[group].length;
      if (count >= this[`${group}Range`][0]) {
        this[`${group}DelDisable`] = false;
      }
      if (count >= 30) {
        this[`${group}AddDisable`] = true;
      }
      if (group === 'data') {
        EventBus.$emit('updateHorizontalFormData', { option: 'add' });
      }
    },
    deleteCurRow(item, group) {
      const index = this.form[group].indexOf(item);
      this.form[group].splice(index, 1);
      const count = this.form[group].length;
      if (count <= this[`${group}Range`][0]) {
        this[`${group}DelDisable`] = true;
      }
      if (count <= 30) {
        this[`${group}AddDisable`] = false;
      }
      if (group === 'data') {
        EventBus.$emit('updateHorizontalFormData', { option: 'delete', index });
      }
    },
    checkLimit() {
      const data = this.form.group;
      const nameList = data.map(n => n.name).filter(n => n);
      const nameListU = Array.from(new Set(nameList));
      if (nameList.length !== nameListU.length) {
        this.$message.error(this.$demoi18n('message.nameRepeated'));
        return false;
      }
      return true;
    },
    apiDataChanged(apiData) {
      if (!apiData) {
        this.nameList = [];
      } else {
        const arr = apiData.map(n => n.s);
        this.nameList = Array.from(new Set(arr));
      }
    },
    changeColorVal() {
      this.form.backgroundColor = this.getValByCompStl('#fff', '#0D263A', '#232323');
    },
    renderTableHeader({ column }) {
      return (
        <el-tooltip placement="top" content={column.label} effect={this.xvueTheme}>
          <span>{column.label}</span>
        </el-tooltip>
      );
    },
  },
};
</script>

<style lang="less" scoped>
@import '../../common/less/panel-property.less';
</style>
<style lang="less" scoped>
.panel-property {
  .content {
    .prop-form {
      padding: 0 10px;

      .slider-number {
        vertical-align: text-bottom;
        padding-right: 5px;
      }

      .slider-number-left {
        vertical-align: text-bottom;
        padding-right: 15px;
      }
      .slider-number-right {
        vertical-align: text-bottom;
        padding-left: 15px;
      }
      :deep(.el-slider) {
        display: inline-block;
        width: 100px;
      }

      :deep(.el-select) {
        .el-input__inner {
          width: 189px;
        }
      }

      .config-table {
        :deep(.el-table__row > td) {
          border: none;
        }
        :deep(.el-table) {
          .cell {
            padding: 0 3px !important;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            .el-input__inner {
              padding: 0 5px !important;
            }
          }
          td,
          th {
            padding: 5px 0 !important;
          }
          :deep(.el-table__row) {
            .el-table_1_column_4,
            .el-table_2_column_6,
            .el-table_2_column_7,
            .el-table_2_column_8 {
              .cell {
                display: flex;
                align-items: center;
                justify-content: center;
              }
            }
          }
        }
      }

      :deep(.el-form-item) {
        margin-bottom: 0;
      }
      .help-description {
        margin-left: 15px;
        color: #26b0ff;
        cursor: pointer;
      }
      .ring-help-description {
        max-width: 2000px !important;
      }
      .range-content {
        :deep(.el-form-item__content) {
          display: flex;
          min-height: 40px;
          align-items: center;
        }
      }
      :deep(.panel-tabs.el-tabs) {
        margin-left: 8px;
        .el-tabs__content {
          overflow: hidden !important;
          position: relative !important;
        }
        .el-tabs__active-bar {
          left: 0;
        }
      }
      .input-number {
        width: 80px;
        :deep(.el-input-number__decrease) {
          width: 19px;
          background-color: #fff;
        }
        :deep(.el-input-number__increase) {
          width: 19px;
          background-color: #fff;
        }
        :deep(.el-input__inner) {
          padding-left: 19px;
          padding-right: 19px;
        }
      }
      .input-number-left {
        margin-right: 25px;
      }

      .color-radio-group {
        background-color: #eeeeee;
        :deep(.el-radio-button__inner) {
          display: inline-block;
          padding: 2px 2px;
          border: 0;
          border-radius: 0;
          height: 24px;
          margin: 2px 2px;
          background: #eeeeee;
        }
        :deep(.is-active) {
          .el-radio-button__inner {
            background-color: #409eff;
          }
        }
      }
      .top-btns {
        .base-option {
          display: inline-block;
          margin-left: 10px;
        }
      }
    }
  }
}
</style>

<style lang="less" scoped>
@import './panel-property.less';
</style>
